<?php
namespace haibao\cms\data;

use \haibao\cms\model\data\SphinxDb as SphinxDbModel;
class SphinxDb extends \haibao\cms\data\BaseMysql{
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\SphinxDb');
	}
	
	public function getHighLightInfo($ids,$type){
		$data = array();
		if ($ids){
			$sql = 'select RecordId,Title,Content,Type from SphinxDb where Type='.$type.' and RecordId in ('.implode(',',$ids).')';
			$result = $this->query($sql);
			while ($row = $result->fetch_assoc()){
				$model = new \haibao\cms\model\data\SphinxDb();
				$model->loadArray($row);
				array_push($data,$model);
			}
		}
		
		return $data;
	}
	
	public function searchByFilter($filter){
		$ids = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		if (!empty($result['matches'])){
			$filter->getPager()->setResultCount($result['total']);
			foreach ($result['matches'] as $match){
				$model = new \haibao\cms\model\data\SphinxDb();
				$model->Type = $match['attrs']['type'];
				$model->RecordId = $match['attrs']['recordid'];
				array_push($ids,$model);
			}
		}
		
		return $ids;	
	}
	
	public function searchImageList($bannerIds,$pager){
		$data = array();
		$countSql = 'select count(DISTINCT q1.Id) as cnt';
		$innerSql = ' from SphinxDb q1 where q1.Status = '.SphinxDbModel::STATUS_ENABLE;
		
		foreach ($bannerIds as $key=>$bannerId){
			$bannerIds[$key] = $this->escape($bannerId);
		}
		
		$innerSql .= ' and q1.PrimaryTagParentId IN ('.implode(',',$bannerIds).')';
		$innerSql .= ' and ( (q1.Type = '.SphinxDbModel::TYPE_ARTICLE.' and q1.Level >= 4) or (q1.Type = '.SphinxDbModel::TYPE_IMAGE.' and q1.Level >= 4) )';
		$countSql .= $innerSql;
		$result = $this->query($countSql);
		$cnt = 0;
		while ($result->fetch_assoc()){
			$cnt = $result->getData('cnt');
			$pager->setResultCount($cnt);
		}
		
		if ($cnt){
			$sql = 'select q1.RecordId RecordId,q1.PrimaryTagId as PrimaryTagId,q1.Type'.$innerSql.' order by q1.ShowTime desc';
			$sql .= ' limit '.($pager->getCurrentPage() - 1)*$pager->getPageSize().','.$pager->getPageSize().'';
			$result = $this->query($sql);
			while($row = $result->fetch_assoc()){
				$model = new SphinxDbModel();
				$model->loadArray($row);
				array_push($data,$model);
			}
		}
		
		return $data;
	}
	
	public function highLight($contentArr,$keyword,$options = array()){
		$sengine = new \haibao\cms\sengine\SphinxDb();
	
		return $sengine->highLight($contentArr,$keyword,$options);
	}
}